import { create } from 'zustand';

export interface Role {
  id: string;
  name: string;
  description: string;
  permissions: string[];
}

export interface User {
  id: string;
  name: string;
  email: string;
  department: string;
  roles: string[];
  lastLogin: string;
  status: 'active' | 'inactive';
}

export interface Resource {
  id: string;
  name: string;
  description: string;
  type: string;
}

interface PermissionState {
  roles: Role[];
  users: User[];
  resources: Resource[];
  loading: boolean;
  error: string | null;
  fetchData: () => Promise<void>;
  addRole: (role: Omit<Role, 'id'>) => Promise<Role>;
  updateRole: (id: string, role: Partial<Role>) => Promise<void>;
  deleteRole: (id: string) => Promise<void>;
  addUser: (user: Omit<User, 'id'>) => Promise<User>;
  updateUser: (id: string, user: Partial<User>) => Promise<void>;
  deleteUser: (id: string) => Promise<void>;
}

export const usePermissionStore = create<PermissionState>((set, get) => ({
  roles: [
    { id: 'admin', name: '管理员', description: '系统管理员，拥有所有权限', permissions: ['doc_read', 'doc_write', 'doc_delete', 'user_manage', 'role_manage', 'system_config'] },
    { id: 'editor', name: '编辑者', description: '可以创建和编辑文档', permissions: ['doc_read', 'doc_write'] },
    { id: 'viewer', name: '查看者', description: '只能查看文档', permissions: ['doc_read'] },
  ],
  users: Array.from({ length: 10 }).map((_, i) => ({
    id: `user-${i}`,
    name: `用户${i}`,
    email: `user${i}@example.com`,
    department: ['技术部', '市场部', '人力资源', '财务部'][Math.floor(Math.random() * 4)],
    roles: i === 0 ? ['admin'] : i < 3 ? ['editor'] : ['viewer'],
    lastLogin: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
    status: Math.random() > 0.2 ? 'active' : 'inactive',
  })),
  resources: [
    { id: 'doc_read', name: '文档查看', description: '查看文档的权限', type: '文档' },
    { id: 'doc_write', name: '文档编辑', description: '创建和编辑文档的权限', type: '文档' },
    { id: 'doc_delete', name: '文档删除', description: '删除文档的权限', type: '文档' },
    { id: 'user_manage', name: '用户管理', description: '管理用户的权限', type: '用户' },
    { id: 'role_manage', name: '角色管理', description: '管理角色的权限', type: '系统' },
    { id: 'system_config', name: '系统配置', description: '配置系统的权限', type: '系统' },
  ],
  loading: false,
  error: null,
  
  fetchData: async () => {
    set({ loading: true, error: null });
    
    try {
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 数据已经在初始状态中定义，所以这里只是模拟加载完成
      set({ loading: false });
    } catch (error) {
      set({ error: '获取权限数据失败', loading: false });
    }
  },
  
  addRole: async (role) => {
    set({ loading: true, error: null });
    
    try {
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const newRole: Role = {
        ...role,
        id: `role-${Date.now()}`,
      };
      
      set(state => ({
        roles: [...state.roles, newRole],
        loading: false,
      }));
      
      return newRole;
    } catch (error) {
      set({ error: '添加角色失败', loading: false });
      throw error;
    }
  },
  
  updateRole: async (id, role) => {
    set({ loading: true, error: null });
    
    try {
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 500));
      
      set(state => ({
        roles: state.roles.map(r => r.id === id ? { ...r, ...role } : r),
        loading: false,
      }));
    } catch (error) {
      set({ error: '更新角色失败', loading: false });
      throw error;
    }
  },
  
  deleteRole: async (id) => {
    set({ loading: true, error: null });
    
    try {
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 500));
      
      set(state => ({
        roles: state.roles.filter(r => r.id !== id),
        loading: false,
      }));
    } catch (error) {
      set({ error: '删除角色失败', loading: false });
      throw error;
    }
  },
  
  addUser: async (user) => {
    set({ loading: true, error: null });
    
    try {
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const newUser: User = {
        ...user,
        id: `user-${Date.now()}`,
      };
      
      set(state => ({
        users: [...state.users, newUser],
        loading: false,
      }));
      
      return newUser;
    } catch (error) {
      set({ error: '添加用户失败', loading: false });
      throw error;
    }
  },
  
  updateUser: async (id, user) => {
    set({ loading: true, error: null });
    
    try {
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 500));
      
      set(state => ({
        users: state.users.map(u => u.id === id ? { ...u, ...user } : u),
        loading: false,
      }));
    } catch (error) {
      set({ error: '更新用户失败', loading: false });
      throw error;
    }
  },
  
  deleteUser: async (id) => {
    set({ loading: true, error: null });
    
    try {
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 500));
      
      set(state => ({
        users: state.users.filter(u => u.id !== id),
        loading: false,
      }));
    } catch (error) {
      set({ error: '删除用户失败', loading: false });
      throw error;
    }
  },
})); 